#include "music_player.h"
// MusicPlayerWidget.cpp
#include <QStyle>

MusicPlayerWidget::MusicPlayerWidget(QWidget* parent)
    : QWidget(parent), currentPlaylistIndex(-1), isPlaying(false)
{
    setupUI();
    setupConnections();

    // Initialize media player
    mediaPlayer = new QMediaPlayer(this);
    audioOutput = new QAudioOutput(this);
    mediaPlayer->setAudioOutput(audioOutput);

    // Set initial volume
    audioOutput->setVolume(0.5);
    volumeSlider->setValue(50);
}

MusicPlayerWidget::~MusicPlayerWidget()
{
}

void MusicPlayerWidget::setupUI()
{
    mainLayout = new QVBoxLayout(this);

    // Create playlist and request list
    QHBoxLayout* listsLayout = new QHBoxLayout();

    // Playlist section
    QVBoxLayout* playlistLayout = new QVBoxLayout();
    playlistLayout->addWidget(new QLabel("播放列表"));
    playlistWidget = new QListWidget();
    playlistLayout->addWidget(playlistWidget);

    // Request list section
    QVBoxLayout* requestLayout = new QVBoxLayout();
    requestLayout->addWidget(new QLabel("点播列表"));
    requestListWidget = new QListWidget();
    requestLayout->addWidget(requestListWidget);

    listsLayout->addLayout(playlistLayout);
    listsLayout->addLayout(requestLayout);

    mainLayout->addLayout(listsLayout);

    // Song info
    infoLayout = new QHBoxLayout();
    currentSongLabel = new QLabel("未选择歌曲");
    currentTimeLabel = new QLabel("00:00");
    totalTimeLabel = new QLabel("00:00");

    infoLayout->addWidget(currentSongLabel, 1);
    infoLayout->addWidget(currentTimeLabel);
    infoLayout->addWidget(new QLabel("/"));
    infoLayout->addWidget(totalTimeLabel);

    mainLayout->addLayout(infoLayout);

    // Progress slider
    progressSlider = new QSlider(Qt::Horizontal);
    mainLayout->addWidget(progressSlider);

    // Control buttons
    controlLayout = new QHBoxLayout();

    addSongsButton = new QPushButton("添加歌曲");
    playPauseButton = new QPushButton("播放");
    previousButton = new QPushButton("上一首");
    nextButton = new QPushButton("下一首");
    addToRequestButton = new QPushButton("添加到点播");

    // Volume control
    volumeSlider = new QSlider(Qt::Horizontal);
    volumeSlider->setMaximum(100);
    volumeSlider->setFixedWidth(100);

    controlLayout->addWidget(addSongsButton);
    controlLayout->addWidget(previousButton);
    controlLayout->addWidget(playPauseButton);
    controlLayout->addWidget(nextButton);
    controlLayout->addWidget(addToRequestButton);
    controlLayout->addWidget(new QLabel("音量:"));
    controlLayout->addWidget(volumeSlider);
    controlLayout->addStretch();

    mainLayout->addLayout(controlLayout);

    setLayout(mainLayout);
    setWindowTitle("音乐播放器");
    resize(600, 400);
}

void MusicPlayerWidget::setupConnections()
{
    connect(addSongsButton, &QPushButton::clicked, this, &MusicPlayerWidget::addSongsToPlaylist);
    connect(playPauseButton, &QPushButton::clicked, this, &MusicPlayerWidget::playPause);
    connect(nextButton, &QPushButton::clicked, this, &MusicPlayerWidget::playNext);
    connect(previousButton, &QPushButton::clicked, this, &MusicPlayerWidget::playPrevious);
    connect(addToRequestButton, &QPushButton::clicked, this, &MusicPlayerWidget::playSelectedSong);

    connect(playlistWidget, &QListWidget::itemDoubleClicked, this, &MusicPlayerWidget::playSelectedSong);

    connect(volumeSlider, &QSlider::valueChanged, this, [this](int value) {
        audioOutput->setVolume(value / 100.0);
        });
}

void MusicPlayerWidget::addSongsToPlaylist()
{
    QStringList fileNames = QFileDialog::getOpenFileNames(this,
        "选择音乐文件",
        QDir::homePath(),
        "音频文件 (*.mp3 *.wav *.ogg *.flac)");

    for (const QString& fileName : fileNames) {
        QFileInfo fileInfo(fileName);
        playlistWidget->addItem(fileInfo.fileName());

        // Store the full path in data role
        QListWidgetItem* item = playlistWidget->item(playlistWidget->count() - 1);
        item->setData(Qt::UserRole, QUrl::fromLocalFile(fileName));
    }

    if (currentPlaylistIndex == -1 && playlistWidget->count() > 0) {
        currentPlaylistIndex = 0;
    }
}

void MusicPlayerWidget::playSelectedSong()
{
    QListWidget* sourceList = qobject_cast<QListWidget*>(sender());
    if (!sourceList) {
        // If called from button, use the focused list
        sourceList = playlistWidget->hasFocus() ? playlistWidget : requestListWidget;
    }

    if (sourceList->currentRow() >= 0) {
        QListWidgetItem* item = sourceList->currentItem();
        QUrl source = item->data(Qt::UserRole).toUrl();

        mediaPlayer->setSource(source);
        mediaPlayer->play();
        isPlaying = true;
        playPauseButton->setText("暂停");

        // Update current song info
        currentSongLabel->setText(item->text());

        // If playing from request list, move to playlist
        if (sourceList == requestListWidget) {
            playlistWidget->addItem(item->text());
            QListWidgetItem* newItem = playlistWidget->item(playlistWidget->count() - 1);
            newItem->setData(Qt::UserRole, source);

            delete requestListWidget->takeItem(requestListWidget->currentRow());

            currentPlaylistIndex = playlistWidget->count() - 1;
        }
        else {
            currentPlaylistIndex = sourceList->currentRow();
        }

        // Connect media player signals for the new song
        connect(mediaPlayer, &QMediaPlayer::positionChanged, this, &MusicPlayerWidget::updatePlaybackPosition);
        connect(mediaPlayer, &QMediaPlayer::durationChanged, this, &MusicPlayerWidget::updateDuration);
        connect(mediaPlayer, &QMediaPlayer::playbackStateChanged, this, &MusicPlayerWidget::updatePlaybackStatus);
    }
}

void MusicPlayerWidget::playPause()
{
    if (mediaPlayer->playbackState() == QMediaPlayer::PlayingState) {
        mediaPlayer->pause();
        isPlaying = false;
        playPauseButton->setText("播放");
    }
    else {
        if (mediaPlayer->source().isEmpty() && playlistWidget->count() > 0) {
            // If no song is loaded but playlist has items, play the first one
            playlistWidget->setCurrentRow(0);
            playSelectedSong();
        }
        else {
            mediaPlayer->play();
            isPlaying = true;
            playPauseButton->setText("暂停");
        }
    }
}

void MusicPlayerWidget::playNext()
{
    if (playlistWidget->count() == 0) return;

    currentPlaylistIndex = (currentPlaylistIndex + 1) % playlistWidget->count();
    playlistWidget->setCurrentRow(currentPlaylistIndex);
    playSelectedSong();
}

void MusicPlayerWidget::playPrevious()
{
    if (playlistWidget->count() == 0) return;

    currentPlaylistIndex = (currentPlaylistIndex - 1 + playlistWidget->count()) % playlistWidget->count();
    playlistWidget->setCurrentRow(currentPlaylistIndex);
    playSelectedSong();
}

void MusicPlayerWidget::updatePlaybackPosition(qint64 position)
{
    if (!progressSlider->isSliderDown()) {
        progressSlider->setValue(position);
    }

    QTime currentTime(0, 0, 0);
    currentTime = currentTime.addMSecs(position);
    currentTimeLabel->setText(currentTime.toString("mm:ss"));
}

void MusicPlayerWidget::updateDuration(qint64 duration)
{
    progressSlider->setRange(0, duration);

    QTime totalTime(0, 0, 0);
    totalTime = totalTime.addMSecs(duration);
    totalTimeLabel->setText(totalTime.toString("mm:ss"));
}

void MusicPlayerWidget::seekPosition(int position)
{
    mediaPlayer->setPosition(position);
}

void MusicPlayerWidget::updatePlaybackStatus()
{
    if (mediaPlayer->playbackState() == QMediaPlayer::StoppedState &&
        mediaPlayer->mediaStatus() == QMediaPlayer::EndOfMedia) {
        playNext();
    }
}

void MusicPlayerWidget::updateCurrentSongInfo()
{
    if (currentPlaylistIndex >= 0 && currentPlaylistIndex < playlistWidget->count()) {
        QListWidgetItem* item = playlistWidget->item(currentPlaylistIndex);
        currentSongLabel->setText(item->text());
    }
}